package com.permission.common;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.permission.util.JsonMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Http前后请求监听工具
 * 用于参数请求参数的记录
 * 注意：一些敏感数据不必记录
 * @author jing 
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter{

	/*
	 * 在请求执行前的时候调用的方法
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求路径
		String url = request.getRequestURI().toString();
		//获取请求参数
		Map parameterMap = request.getParameterMap();
		log.info("请求开始  URL:{},params:{}",url,JsonMapper.objToString(parameterMap));		
		return true;
	}

	/*
	 * 当请求正常结束的时候(不包括异常)，调用的方法
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		/*String url = request.getRequestURI().toString();
		Map parameterMap = request.getParameterMap();
		log.info("request finish url:{},params:{}",url,JsonMapper.objToString(parameterMap));*/	
		//afterCompletion的功能已经覆盖了该方法
		
		removeThreadLocalInfo();
	}

	/*
	 * 在请求响应结束的时候调用的方法，包括异常的情况下
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String url = request.getRequestURI().toString();
		Map parameterMap = request.getParameterMap();
		log.info("请求结束 URL:{},params:{}",url,JsonMapper.objToString(parameterMap));		
		
		removeThreadLocalInfo();
	}
	
	public void removeThreadLocalInfo() {
        RequestHolder.remove();
    }
	
	/*
	 * 将HttpInterceptor交给Spring管理
	 * 在springmvc.xml文件下添加该bean
	 * <!-- 自定义的Http请求前后加监听工具 -->
	 *	<mvc:interceptors>
	 *		<bean class="com.permission.common.HttpInterceptor" />
	 *	</mvc:interceptors>
	 *	
	 */
	
}
